<script lang="ts">
export default {
  name: "RecordFormHeader"
}
</script>

<template>
  <el-form ref="queryFormRef" :inline="true" :model="queryParams">
    <el-form-item prop="edgeId">
      <el-input v-model="queryParams.edgeId" clearable placeholder="Edge ID" @keyup.enter="handleQuery"/>
    </el-form-item>
    <el-form-item v-for="(item,index) in queryParams.fields">
      <el-input :key="index" v-model="queryParams.fields[index].value"
                v-model:placeholder="queryParams.fields[index].key"/>
    </el-form-item>
    <el-form-item>
      <el-button :icon="Search" type="primary" @click="handleQuery">搜索</el-button>
      <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {onMounted, reactive, toRefs} from "vue";

import {Search, Refresh} from '@element-plus/icons-vue';
import {RecordQueryParam, ValueParam} from "@/api/cloud/table/record/types";
import {useRouter} from "vue-router";
import {EntityTable} from "@/api/cloud/table/schema/types";

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({setEntity});

const emit = defineEmits(['query']);// 定义组件的事件通知

// 数据状态：定义
let dataState = reactive({
  // 字段信息
  table: {} as EntityTable,
  // 查询参数
  queryParams: {fields: [], pageNum: 1, pageSize: 10} as RecordQueryParam,
});

// 数据状态：双向引用
const {
  // 字段信息
  table,
  // 查询参数
  queryParams,
} = toRefs(dataState);

function handleQuery() {
  emit('query', 'header', queryParams.value);
}

function setEntity(entityType: string, table: EntityTable) {
  dataState.queryParams.entityType = entityType;
  dataState.table = table;

  queryParams.value.fields = [];
  for (let field of Object.values(table.fields)) {
    if (field.key !== 'index'){
      continue
    }

    let param = {} as ValueParam;
    param.key = field.name;

    queryParams.value.fields.push(param);
  }
}

function resetQuery() {
  dataState.queryParams.edgeId = undefined;
  let fields = dataState.queryParams.fields as ValueParam[];
  for (let field of fields) {
    let empty = {} as ValueParam;
    field.value = empty.value;
  }
  emit('query', 'header', queryParams.value);
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  const router = useRouter();
  const queryParam = router.currentRoute.value.query;
  dataState.queryParams.entityType = queryParam.name as string;
});

</script>
